// 引入express
const express = require('express')
// 引入连接池模块
const pool = require('../pool.js')
const router = express.Router()
// 查找
// http://localhost:3000/room/
router.get('/', (req, res, next) => {
  pool.query('select * from qnls_roomlist', (err, r) => {
    if (err) {
      return next(err)
    }
    res.send({ code: 200, msg: '所有房间', data: r })
  })
})
router.get('/info/query', (req, res, next) => {
  // 获取params传递的参数
  let { hid } = req.query

  // 执行SQL命令
  pool.query('select * from qnls_roomlist where hid=?', [hid], (err, r) => {
    if (err) {
      // 如果出现mysql错误，把错误交个下一个中间件
      // 阻止往后执行
      return next(err)
    }
    console.log(r)
    res.send({ code: 200, msg: '查询成功', data: r })
  })
})

router.get('/infor/query', (req, res, next) => {
  // 获取params传递的参数
  var { rid } = req.query
  // 执行SQL命令
  pool.query('select * from qnls_roomlist where rid=?', [rid], (err, r) => {
    if (err) {
      // 如果出现mysql错误，把错误交个下一个中间件
      // 阻止往后执行
      return next(err)
    }
    console.log(r)
    res.send({ code: 200, msg: '查询成功', data: r })
  })
})
// 添加
// http://localhost:3000/room/add
router.post('/add', (req, res, next) => {
  var obj = req.body
  pool.query('insert into qnls_roomlist set ?', [obj], (err, r) => {
    if (err) {
      return next(err)
    }
    res.send({ code: 200, msg: '订单添加成功' })
  })
})
// 修改
// http://localhost:3000/order/put
router.put('/put', (req, res, next) => {
  var obj = req.body
  pool.query(
    'update qnls_roomlist set ? where rid=?',
    [obj, obj.rid],
    (err, r) => {
      if (err) {
        return next(err)
      }
      if (r.changedRows === 0) {
        res.send({ code: 400, msg: '修改失败' })
      } else {
        res.send({ code: 200, msg: '修改成功' })
      }
    }
  )
})
// 删除
// http://localhost:3000/room/del/2
router.delete('/del/:rid', (req, res, next) => {
  // 获取params传递参数
  var obj = req.params
  pool.query('delete from qnls_roomlist where rid=?', [obj.rid], (err, r) => {
    if (err) {
      return next(err)
    }
    if (r.affectedRows === 0) {
      res.send({ code: 400, msg: '删除失败' })
    } else {
      res.send({ code: 200, msg: '删除成功' })
    }
  })
})
module.exports = router
